package edu.dublbo.commons.exception;

import edu.dublbo.commons.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLException;

/**
 * 异常通用处理
 */
@Slf4j
public class GlobalExceptionAdvice {

    /**
     * IllegalArgumentException 异常处理返回 json
     * 返回状态码：400
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({IllegalArgumentException.class})
    public Result<Object> badRequestException(IllegalArgumentException e) {
        return handle("参数解析失败", e);
    }

    /**
     * 返回状态码：405
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Result<Object> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return handle("不支持的请求方法", e);
    }

    /**
     * 返回状态码：415
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public Result<Object> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        return handle("不支持当前媒体类型", e);
    }

    /**
     * SQLException SQL异常处理
     * 返回状态码：500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({SQLException.class})
    public Result<Object> handleSQLException(SQLException e) {
        return handle("服务运行 SQL 错误", e);
    }

    /**
     * BusinessException 业务异常处理
     * 返回状态码：500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public Result<Object> handleException(BusinessException e) {
        return handle("业务处理错误", e);
    }

    /**
     * 所有异常统一处理
     * 返回状态码：500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        return handle("服务器未知错误", e);
    }

    private Result<Object> handle(String msg, Exception e) {
        log.error(msg, e);
        return Result.fail(msg);
    }
}
